#include "record_util.h"
#include <sys/types.h> 
#include <sys/wait.h>
#include "hifunction.h"
#include "hilog.h"
#include "http_client.h"

RecordUtil::RecordUtil()
{
    pid_ = -1;
    unicode_ = 0;
    user_ = "";
    flowUrl_ = "";
    path_ = "";
    callbackurl_ = "";
    otherParam_ = "";
    fp_ = NULL;
    runflag_ = false;
}

RecordUtil::~RecordUtil()
{
}

void RecordUtil::start_record(int& unicode, string &user, string &flowUrl, string &path, string &callbackurl, string &otherParam)
{
    if (pipe(fd))
    {
        hi_error("create pipe failed");
        return;
    }

    unicode_ = unicode;
    user_ = user;
    flowUrl_ = flowUrl;
    path_ = path;
    callbackurl_ = callbackurl;
    otherParam_ = otherParam;

    pid_t pid = fork();
    if (pid < 0)
    {
        hi_error("create record sub process failed.");
    }
    else if (pid == 0)
    {        
        //子进程

        /********创建存储目录*********/
        string strdir = path.substr(0, path.find_last_of("/"));
        mkdirs(strdir.c_str());

        /********开始录制************/
        //exmple: "ffmpeg -i rtmp://192.168.1.238/live/xw -vcodec copy -acodec copy -loglevel quiet -y test.mp4";
        stringstream cmd_record;
        cmd_record << get_app_path() << "ffmpeg -rw_timeout 8000000 -i " << flowUrl_ << " -vcodec copy -acodec copy -loglevel quiet -y " << path_;
        hi_trace("cmd: %s", cmd_record.str().c_str());
        if ((fp_ = popen(cmd_record.str().c_str(), "w")) == NULL)
        {
            hi_warn("popen error!\n");
            return;
        }
        
        close(fd[1]);
        char message[100] = {0};
        read(fd[0], message, 100);
        if (fputs("q", fp_) < 0)
        {
            hi_warn("exit failed.");
            return;
        }
        else {          
            hi_trace("stop record finished.");
        }
    }
    else {
        pid_ = pid;
        runflag_ = true;
        start("RecordUtil");                
    }
    return;
}

void RecordUtil::stop_record()
{
    runflag_ = false;
    //通知子进程停止录制 
    close(fd[0]);
    char *msg = "stop";
    write(fd[1], msg, 4);
    
    if(pid_) {
        int status = 0;
        //等待录制文件正常结束
        waitpid(pid_, &status, 0);
        system("sync");  
        sleep(2);
        //抓拍五张图片 隔3秒抓拍一张
        string out_name = path_.substr(0, path_.find_last_of("."));
        int gap_seconds = 3;
        for(int i = 0 ; i < 5 ; i++) {
            stringstream save_image;
            save_image << "./ffmpeg -i ";                
            save_image << path_;
            save_image << " -y -f image2 -ss "<<(i+1)*gap_seconds<<" ";
            save_image <<out_name;
            save_image << "_jpg";
            save_image << (i+1);
            save_image << ".jpg";
            system(save_image.str().c_str());     //执行ffmpeg保存指令
            hi_trace("ffmpeg snatshop cmd %s",save_image.str().c_str());
        }                      
    }
  
    //通知平台录制完成
    // stringstream http_url;
    // http_url<<callbackurl_<<"?"<<"uniqueCode="<<unicode_<<"&";
    // http_url<<"user="<<user_<<"&";
    // http_url<<"path="<<path_<<"&";
    // http_url<<"otherParam="<<otherParam_;

    // string eurl = http_url_encode(http_url.str());
    // hi_trace("stop http encorde url: %s", eurl.c_str());
    // HttpClient::SendReq(http_url.str());        

    return;
}

void RecordUtil::process()
{
    long long record_time = 0;
    while(runflag_) {
        //定时检测录像时间
        struct timeval temp;
        temp.tv_sec = 60;
        temp.tv_usec = 0;
        select(0, NULL, NULL, NULL, &temp);
        
        //单个文件最大录制时长3小时
        record_time++;
        if(record_time > 3*60*60)
        {//停止录制
            hi_warn("max record time come url: %d", flowUrl_.c_str());
            stop_record();
        }
    }
}